#include <iostream>

using std::cout;
using std::endl;

//内部类
class Singleton{
public:
    static Singleton *getInstance(){
        if(_pInstance==nullptr)
            _pInstance=new Singleton();
        return _pInstance;
    }

private:
    class AutoRelease{
    public:
        AutoRelease(){
            cout<<"at"<<endl;
        }

        ~AutoRelease(){
            cout<<"~at"<<endl;
            if(Singleton::_pInstance){
                delete Singleton::_pInstance;
                Singleton::_pInstance=nullptr;
            }
            else
                cout<<"不要释放两次"<<endl;
        }
    };

private:
    Singleton(){
        cout<<"单例模式"<<endl;
    }

    ~Singleton(){
        cout<<"手动释放"<<endl;
    }

private:
    static Singleton *_pInstance;

    static AutoRelease ar;
    //如果只是普通的ar，放在栈区，形成死锁:
    //要先执行大析构，才释放掉这个栈上的数据成员
    //但要大析构，必须先让系统自动回收栈上的成员，回收时执行ar的析构函数，释放指针，
    //才能完成大析构
    //而位于静态区，进程结束时会自动释放ar，此时顺便delete单例模式
};

Singleton *Singleton::_pInstance=nullptr;
Singleton::AutoRelease Singleton::ar;

void test(){
    Singleton *s1= Singleton::getInstance();
}

int main()
{   
    test();
    return 0;
}

